package com.tang.common.config;

import com.tang.common.async.CommonAsync;
import com.tang.common.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.tang.common.interceptor.frequency.EntranceFilterHandlerActuator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口限制过滤注册
 * @author tang
 * @date 2022/1/21 13:36
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    private EntranceFilterHandlerActuator entranceFilterHandlerActuator;

    @Autowired
    private CommonAsync commonAsync;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //接口限制拦截器,这里没用使用aop来实现接口限制功能,而使用拦截器链路实现
        registry.addInterceptor(new HandlerInterceptor() {
                    @Override
                    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                        //接口访问次数限制/统计/ip限流
                        entranceFilterHandlerActuator.actuator(request,response);
                        //在线人数统计
                        commonAsync.numberOfPeopleOnline(
                                SecurityContextHolder.getContext().getAuthentication(),
                                CommonUtils.getIpAddr(request),
                                request.getHeader("User-Agent"));
                        return true;
                    }
                }).order(Integer.MAX_VALUE)
                //排除不需要访问限制的接口
                .excludePathPatterns("/favicon.ico")
                .excludePathPatterns("/doc.html")
                .excludePathPatterns("/swagger-resources")
                .excludePathPatterns("/webjars/**")
                .excludePathPatterns("/v2/api-docs/**")
                .excludePathPatterns("/captcha")
                .excludePathPatterns("/login")
                .excludePathPatterns("/error")
                .excludePathPatterns("/test/**");

    }

}
